import axios from 'axios'
import { toast } from '~/composables/util'
import { getToken } from '~/composables/auth'
import { router } from '~/router'
import { getStorage } from '~/composables/storage'
// import { computed } from 'vue'
//

// const BAASEAPI = getStorage('isLine')
// const CBAASEAPI = computed(() => !BAASEAPI ? import.meta.env.VITE_APP_BASE_API : import.meta.env.VITE_APP_BASELOCALITY_API)

// watch(
//   () => getStorage('isLine'),
//   () => {
//     console.log('isLine')
//   }
// )


const isLine = getStorage('isLine')
const wifiIP = getStorage('wifiIP')
const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Huawei|Honor|EMUI|HarmonyOS|MicroMessenger|Windows Phone|Mobile|SymbianOS|Nokia|UCWEB|Opera Mobi|Maemo|webOS|webOS|BlackBerry|Tablet|Mobile Safari/i.test(navigator.userAgent)


let wifiIPUrl = `http://${wifiIP}:30800`

const MobileURL = wifiIP && isMobile ? wifiIPUrl : import.meta.env.VITE_APP_BASELOCALITY_API

const apiURL = isLine ? MobileURL : import.meta.env.VITE_APP_BASE_API


console.log(wifiIP, 'wifiIP-----------------')
console.log(MobileURL, 'MobileURL-----------------')
console.log(apiURL, 'apiURL-----------------')



const service = axios.create({
  // baseURL: import.meta.env.VITE_APP_BASELOCALITY_API,
  // baseURL: isLine ? import.meta.env.VITE_APP_BASELOCALITY_API : import.meta.env.VITE_APP_BASE_API
  baseURL: apiURL
})




// 添加请求拦截器
service.interceptors.request.use((config) => {

  // 往header头自动添加token
  // const token = getToken()
  const token = getStorage('token')

  if (token)
    config.headers.token = token

  return config
}, (error) => {
  // 对请求错误做些什么
  return Promise.reject(error)
})

// 添加响应拦截器
service.interceptors.response.use((response) => {
  if (response.request.responseType == 'blob')
    return response.data

  // 非法token
  if (response.data.code === '10000') {
    toast(response.data.msg, 'error')
    console.log('非法token')
    // store.dispatch('clearFn')
    return router.replace('/login')
  }


  if (response.data.code === '0000')
    return response.data.data

  else
    toast(response.data.msg, 'error')
  return Promise.reject('其他报错')
  // return response.request.responseType == "blob" ? response.data : response.data.data;
}, (error) => {
  const msg = error.response.data.msg || '请求失败'

  if (msg == '非法token，请先登录！')
    // store.dispatch('clearFn').finally(() => location.reload())

    toast(msg, 'error')

  return Promise.reject(error)
})

export default service
